<script setup lang="ts">
import { useRoute } from "vue-router";
import { onMounted, ref, computed } from "vue";
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { useDisplay, useTheme } from 'vuetify'

interface BlogPost {
    id?: number;
    name: string;
    content: string;
    status: '0' | '1';
    authorId?: number;
    typeId?: number;
    tagIds: string[];
    topAssert: '0' | '1';
    seoKey: string;
    seoTitle: string;
    seoDesc: string;
    brief: string;
    coverUrl: string;
}

const route = useRoute();
const { mobile } = useDisplay()

const blogPost = ref<BlogPost>({
    name: '',
    content: '',
    status: '0',
    tagIds: [],
    topAssert: '0',
    seoKey: '',
    seoTitle: '',
    seoDesc: '',
    brief: '',
    coverUrl: ''
});

const loading = ref(false);
const keywordInput = ref('');
const previewImage = ref<string>('');

const theme = useTheme()

// 计算编辑器主题
const editorTheme = computed(() => {
    return theme.global.current.value.dark ? 'dark' : 'light'
})

// 获取博客详情
const fetchBlogDetail = async (id: string) => {
    try {
        loading.value = true;
        // TODO: 调用获取博客详情API
        // const response = await api.getBlogDetail(id);
        // blogPost.value = response.data;
    } catch (error) {
        // 使用 Vuetify 的 Snackbar 来显示错误信息
        console.error('获取博客详情失败');
    } finally {
        loading.value = false;
    }
};

// 保存博客
const saveBlog = async () => {
    try {
        loading.value = true;
        if (!blogPost.value.name) {
            console.warn('请输入博客标题');
            return;
        }
        if (!blogPost.value.content) {
            console.warn('请输入博客内容');
            return;
        }

        const isEdit = route.params.id;
        // TODO: 调用保存或更新API
        // const response = await (isEdit ? api.updateBlog(blogPost.value) : api.createBlog(blogPost.value));
        console.log(isEdit ? '更新成功' : '创建成功');
    } catch (error) {
        console.error('保存失败');
    } finally {
        loading.value = false;
    }
};

// 处理关键词添加
const addKeyword = () => {
    if (keywordInput.value && !blogPost.value.keywords.includes(keywordInput.value)) {
        blogPost.value.keywords.push(keywordInput.value);
        keywordInput.value = '';
    }
};

// 处理图片上传
const handleImageUpload = (event: any) => {
    if (!event) {
        previewImage.value = '';
        blogPost.value.coverUrl = '';
        return;
    }
    
    const file = event;
    if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            previewImage.value = e.target?.result as string;
            blogPost.value.coverUrl = previewImage.value;
        };
        reader.readAsDataURL(file);
    }
};

// 在 setup 中添加一个控制变量
const showSeo = ref(true); // 默认开启SEO设置

onMounted(() => {
    const { id } = route.params;
    if (id) {
        fetchBlogDetail(id as string);
    }
});
</script>

<template>
    <v-container class="blog-editor">
        <v-card>
            <v-card-title class="d-flex justify-space-between align-center">
                <span>{{ route.params.id ? '编辑博客' : '新增博客' }}</span>
                <v-btn
                    color="primary"
                    :loading="loading"
                    @click="saveBlog"
                >
                    保存
                </v-btn>
            </v-card-title>

            <v-card-text>
                <v-form>
                    <!-- 第一行：标题和SEO开关 -->
                    <v-row>
                        <v-col cols="12" md="9">
                            <v-text-field
                                v-model="blogPost.name"
                                label="文章标题"
                                variant="outlined"
                                :rules="[(v) => !!v || '标题不能为空']"
                            />
                        </v-col>
                        <v-col cols="12" md="3" class="d-flex align-center">
                            <v-switch
                                v-model="showSeo"
                                label="开启SEO"
                                color="primary"
                                hide-details
                            />
                        </v-col>
                    </v-row>

                    <!-- SEO相关字段，使用v-show控制显示/隐藏 -->
                    <div v-show="showSeo">
                        <!-- 第二行：SEO标题和关键词 -->
                        <v-row>
                            <v-col cols="12" md="6">
                                <v-text-field
                                    v-model="blogPost.seoTitle"
                                    label="SEO标题"
                                    variant="outlined"
                                    :rules="[(v) => !v || v.length <= 70 || 'SEO标题不能超过70个字符']"
                                />
                            </v-col>
                            <v-col cols="12" md="6">
                                <v-text-field
                                    v-model="blogPost.seoKey"
                                    label="SEO关键词"
                                    variant="outlined"
                                    :rules="[(v) => !v || v.length <= 60 || 'SEO关键词不能超过60个字符']"
                                />
                            </v-col>
                        </v-row>

                        <!-- 第三行：SEO描述 -->
                        <v-textarea
                            v-model="blogPost.seoDesc"
                            label="SEO描述"
                            variant="outlined"
                            rows="2"
                            :rules="[(v) => !v || v.length <= 150 || 'SEO描述不能超过150个字符']"
                        />
                    </div>

                    <!-- 第四行：文章简介 -->
                    <v-textarea
                        v-model="blogPost.brief"
                        label="文章简介"
                        variant="outlined"
                        rows="2"
                        :rules="[(v) => !v || v.length <= 70 || '文章简介不能超过70个字符']"
                    />

                    <!-- 第五行：分类和标签 -->
                    <v-row>
                        <v-col cols="12" md="4">
                            <v-select
                                v-model="blogPost.typeId"
                                label="文章分类"
                                variant="outlined"
                                :items="[]"
                            />
                        </v-col>
                        <v-col cols="12" md="8">
                            <v-combobox
                                v-model="blogPost.tagIds"
                                label="文章标签"
                                multiple
                                chips
                                variant="outlined"
                            >
                                <template v-slot:chip="{ props, item }">
                                    <v-chip
                                        v-bind="props"
                                        closable
                                        @click:close="blogPost.tagIds = blogPost.tagIds.filter(k => k !== item)"
                                    >
                                        {{ item }}
                                    </v-chip>
                                </template>
                            </v-combobox>
                        </v-col>
                    </v-row>

                    <!-- 第六行：封面图和状态开关 -->
                    <v-row>
                        <v-col cols="12" md="6">
                            <v-file-input
                                label="封面图"
                                variant="outlined"
                                accept="image/*"
                                @update:model-value="handleImageUpload"
                                :show-size="true"
                                prepend-icon="mdi-camera"
                            >
                                <template v-slot:append-inner>
                                    <v-img
                                        v-if="previewImage || blogPost.coverUrl"
                                        :src="previewImage || blogPost.coverUrl"
                                        height="40"
                                        width="40"
                                        cover
                                        class="mt-1"
                                    />
                                </template>
                            </v-file-input>
                        </v-col>
                        <v-col cols="12" md="6" class="d-flex align-center">
                            <v-switch
                                v-model="blogPost.topAssert"
                                label="是否推荐"
                                color="primary"
                                true-value="1"
                                false-value="0"
                                class="me-4"
                            />
                            <v-switch
                                v-model="blogPost.status"
                                :label="blogPost.status === '1' ? '已发布' : '草稿'"
                                color="primary"
                                true-value="1"
                                false-value="0"
                            />
                        </v-col>
                    </v-row>

                    <!-- 第七行：Markdown编辑器 -->
                    <div class="editor-wrapper">
                        <MdEditor
                            v-model="blogPost.content"
                            :style="{ height: mobile ? '400px' : '600px' }"
                            :theme="editorTheme"
                            :preview="true"
                        />
                    </div>
                </v-form>
            </v-card-text>
        </v-card>
    </v-container>
</template>

<style scoped>
.blog-editor {
    padding: 20px;
}

.editor-wrapper {
    margin-top: 20px;
}

:deep(.md-editor) {
    border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
    border-radius: 4px;
}

/* 确保文字在暗色模式下有足够的对比度 */
:deep(.text-high-emphasis) {
    color: rgb(var(--v-theme-on-surface)) !important;
}

/* 适配暗色模式的编辑器样式 */
:deep(.md-editor-dark) {
    --md-bk-color: rgb(var(--v-theme-surface));
    --md-color: rgb(var(--v-theme-on-surface));
    --md-border-color: rgba(var(--v-border-color), var(--v-border-opacity));
}
</style>